#include <cv.h>
#include <highgui.h>
#include <stdlib.h>
#include <stdio.h>


#pragma comment( lib,"cv.lib" )
#pragma comment( lib,"highgui.lib" )
#pragma comment( lib,"cxcore.lib" )


char wndname[]="Demo";
char chessimage[]="1.bmp";


int main(int argc, char **argv)
{
	int i,j,index;
	//int nonum=0;
	FILE *f;
	f=fopen("exchangedata0.txt","r");

	if (f==NULL)
	{
		printf("error");
		return -1;
	}

	int imgw,imgh,imgx,imgy,len;
	float a,b;
	char buf[1024];

	fscanf(f,"%d,%d,%d,%d\n",&imgx,&imgy,&imgw,&imgh);

	int temp=imgw;

	imgw=620;
	imgh=437;

	CvPoint2D32f *m_mapP2I=new CvPoint2D32f[imgw*imgh];
	int n=imgw*imgh;

	for (i=0;i<n;i++)
	{
		m_mapP2I[i].x=-1;
		m_mapP2I[i].y=-1;
	}

	for (int i=0;i<imgh;i++)
	{
		for (int j=0;j<imgw;j++)
		{
			fscanf(f,"%d,%f,%f\n",&index,&a,&b);

			if (index==(i+1)*temp-1)
			{
				fscanf(f,"%d,%f,%f\n",&index,&a,&b);
			}

			int qq=index/temp;
			m_mapP2I[index-qq*(temp-imgw)].x=a;
			m_mapP2I[index-qq*(temp-imgw)].y=b;
		}
		
	}


	IplImage *pImage=cvLoadImage("tifa1.jpg",CV_LOAD_IMAGE_COLOR);
	IplImage *chess=cvLoadImage(chessimage,CV_LOAD_IMAGE_COLOR);
	IplImage *pimg=cvCreateImage(cvSize(chess->width,chess->height),8,3);

	if (pImage->nChannels!=3||pImage->depth!=IPL_DEPTH_8U||pImage->dataOrder!=0)
	{
		return -1;
	}

	cvRectangle(pimg,cvPoint(-1,-1),cvPoint(pimg->width-1,pimg->height-1),CV_RGB(0,0,0),CV_FILLED);
	int height=pimg->height;
	int width=pimg->width;
	int pstep=pimg->widthStep;
	int istep=pImage->widthStep;
	int iheight=pImage->height;
	int iwidth=pImage->width;

	unsigned char *data=(unsigned char*)pimg->imageData;
	unsigned char *sdata=(unsigned char*)pImage->imageData;

	for (j=0;j<imgh;j++)
	{
		for (i=0;i<imgw;i++)
		{
			int idx=i+j*imgw;
			CvPoint2D32f *p=m_mapP2I+idx;

			if ((p->x<iwidth)&&(p->x>=0)&&(p->y<iheight)&&(p->y>=0))
			{
				int poss=(int)(p->y)*istep+(int)(p->x)*3;
				int post=(j+imgy)*pstep+(i+imgx)*3;

				data[post]=sdata[poss];
				data[post+1]=sdata[poss+1];
				data[post+2]=sdata[poss+2];
			}
		}
	}

	cvNamedWindow(wndname,1);
	cvShowImage(wndname,pimg);
	cvWaitKey(0);
	cvReleaseImage(&pImage);
	cvDestroyWindow(wndname);

	return 0;

}